package esms.etonenet.boss1069.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.etonenet.taglibs.component.AjaxPage;
import com.etonenet.taglibs.util.AjaxPageUtil;
import com.etonenet.util.StringUtil;

import esms.etonenet.boss1069.enums.mtmo.MtState;
import esms.etonenet.boss1069.enums.mtmo.RtErrorCode;
import esms.etonenet.boss1069.enums.mtmo.RtState;
import esms.etonenet.boss1069.mtmo.Mt;
import esms.etonenet.boss1069.service.biz.impl.MtService;
import esms.etonenet.boss1069.util.AutocompleteUtil;
import esms.etonenet.boss1069.util.DataExportUtil;
import esms.etonenet.boss1069.util.TilesUtil;
import esms.etonenet.boss1069.web.Autocomplete;
import esms.etonenet.boss1069.web.PageRequest;
import esms.etonenet.boss1069.web.SpecificationCondition;
import esms.etonenet.boss1069.web.SpecificationHelper;
import esms.etonenet.boss1069.web.UrlConstants;
import esms.etonenet.bossoa.entity.CarrierCode;
import esms.etonenet.bossoa.entity.City;
import esms.etonenet.bossoa.entity.Country;
import esms.etonenet.bossoa.entity.Province;
import esms.etonenet.bossoa.repository.CarrierCodeRepository;
import esms.etonenet.bossoa.repository.CityRepository;
import esms.etonenet.bossoa.repository.CountryRepository;
import esms.etonenet.bossoa.repository.ProvinceRepository;
import esms.etonenet.oldboss.entity.OldSpService;
import esms.etonenet.oldboss.entity.OldSpServicePK;
import esms.etonenet.oldboss.repository.OldChannelRepository;
import esms.etonenet.oldboss.repository.OldSpRepository;
import esms.etonenet.oldboss.repository.OldSpServiceRepository;
import springfox.documentation.annotations.ApiIgnore;

@ApiIgnore
@Controller
public class QxxxglMtController {

	private static Logger logger = LoggerFactory.getLogger(QxxxglMtController.class);

	@Resource
	private MtService ttMtService;

	@Resource
	private OldSpRepository spEm;

	@Resource
	private OldChannelRepository channelEm;

	@Resource
	private CountryRepository countryEm;

	@Resource
	private ProvinceRepository provinceEm;

	@Resource
	private CityRepository cityEm;

	@Resource
	private CarrierCodeRepository carrierCodeEm;

	@Resource
	private OldSpServiceRepository spServiceEm;

	/**
	 * 企信下行查询初始化
	 * 
	 * @return
	 */
	@RequestMapping(UrlConstants.QYDX_QXXXGL_MTSELECT_INDEX)
	public ModelAndView mtSelectIndex() {

		ModelAndView mav = new ModelAndView(TilesUtil.getPath(UrlConstants.QYDX_QXXXGL_MTSELECT_INDEX));
		mav.addObject("rtErrorCode", RtErrorCode.toDisplayMap2());
		mav.addObject("smsMtState", MtState.toDisplayMap2());
		mav.addObject("smsRtState", RtState.toDisplayMap2());
		return mav;

	}

	/**
	 * 企信下行查询展示
	 * 
	 * @return
	 */
	@RequestMapping(UrlConstants.QYDX_QXXXGL_MTSELECT_DATA)
	@ResponseBody
	public AjaxPage data(Integer pageNumber, Integer pageSize, final String sortName, final String sortOrder,
			final String spIdName, final String channelId, final String spServiceCode, final String mtState,
			final String mtStat, final String destinationAddr,
			@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") final Date smStartTime,
			@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") final Date smEndTime,
			@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") final Date mcStartTime,
			@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") final Date mcEndTime, final String countryIdName,
			final String provinceIdName, final String cityIdName, final String rtErrorCode,
			final String carrierCodeIdName, final String likeChannelId, HttpServletRequest request, String exportType) {
		Map<String, String[]> map = request.getParameterMap();
		boolean b = map.containsKey("smStartTime");

		List<SpecificationCondition> conditions = new ArrayList<SpecificationCondition>();
		conditions.add(SpecificationCondition.eq("spId", StringUtil.splitMinusFirstGroup(spIdName)));
		conditions.add(SpecificationCondition.eq("spServiceCode", spServiceCode));
		conditions.add(SpecificationCondition.eq("channelId", StringUtil.splitMinusFirstGroup(channelId)));
		if (!b) {
			conditions.add(SpecificationCondition.lessOrEqual("spMtTime",
					DateUtils.truncate(new Date(), Calendar.DAY_OF_MONTH)));
			conditions.add(SpecificationCondition.greater("spMtTime",
					DateUtils.truncate(DateUtils.addDays(new Date(), 1), Calendar.DAY_OF_MONTH)));
		} else {
			if (smStartTime != null)
				conditions.add(SpecificationCondition.greaterOrEqual("spMtTime", smStartTime));
			if (smEndTime != null)
				conditions.add(SpecificationCondition.lessOrEqual("spMtTime", smEndTime));
		}
		if (mcStartTime != null)
			conditions.add(SpecificationCondition.greaterOrEqual("carrierMtTime", mcStartTime));
		if (mcEndTime != null)
			conditions.add(SpecificationCondition.lessOrEqual("carrierMtTime", mcEndTime));
		if (mtState != null)
			conditions.add(SpecificationCondition.eq("mtState", StringUtil.splitMinusFirstGroup(mtState)));
		conditions.add(SpecificationCondition.equalOrLikeIgnoreCase("destinationAddr", destinationAddr));
		conditions.add(SpecificationCondition.eq("countryCode", StringUtil.splitMinusFirstGroup(countryIdName)));
		conditions.add(SpecificationCondition.eq("provinceCode", StringUtil.splitMinusFirstGroup(provinceIdName)));
		conditions.add(SpecificationCondition.eq("cityCode", StringUtil.splitMinusFirstGroup(cityIdName)));
		conditions.add(SpecificationCondition.equalOrLikeIgnoreCase("mtStat", mtStat));
		conditions.add(SpecificationCondition.eq("rtErr", StringUtil.splitMinusFirstGroup(rtErrorCode)));
		conditions.add(SpecificationCondition.eq("carrierCode", StringUtil.splitMinusFirstGroup(carrierCodeIdName)));
		conditions.add(SpecificationCondition.equalOrLikeIgnoreCase("channelId", likeChannelId));

		SpecificationHelper<Mt> sh = new SpecificationHelper<>(conditions, sortOrder, sortName);
		Page<Mt> p = ttMtService.page(sh.createSpecification(), new PageRequest(pageNumber, pageSize));
		for (Mt mt2 : p) {
			displaySpMtBaseInfo(mt2);
		}

		return AjaxPageUtil.toAjaxPage(p.getTotalElements(), p.getContent());

	}

	@RequestMapping(UrlConstants.QYDX_QXXXGL_MTSELECT_EXPORT)
	public void export(HttpServletResponse response, HttpServletRequest request,
			@RequestParam(defaultValue = "0") Integer pageNumber, @RequestParam(defaultValue = "20") Integer pageSize,
			final String sortName, final String sortOrder, final String spIdName, final String channelId,
			final String spServiceCode, final String mtState, final String mtStat, final String destinationAddr,
			@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") final Date smStartTime,
			@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") final Date smEndTime,
			@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") final Date mcStartTime,
			@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") final Date mcEndTime, final String countryIdName,
			final String provinceIdName, final String cityIdName, final String rtErrorCode,
			final String carrierCodeIdName, final String exportType, final String likeChannelId) {

		List<Mt> list = new ArrayList<Mt>();
		for (int i = 0, pages = 1; i <= pages; i++) {
			AjaxPage page = data(i + 1, 1000, sortName, sortOrder, spIdName, channelId, spServiceCode, mtState, mtStat,
					destinationAddr, smStartTime, smEndTime, mcStartTime, mcEndTime, countryIdName, provinceIdName,
					cityIdName, rtErrorCode, carrierCodeIdName, likeChannelId, request, exportType);

			if (pages == 1)
				pages = Integer.parseInt(page.getTotal().toString()) / 1000;
			list.addAll(page.getRows());
		}
		for (Mt mt : list) {
			if (StringUtil.isNotBlank(mt.getRtErr()))
				mt.setRtErr(RtErrorCode.fromValue(mt.getRtErr()).getName());
		}
		String[] exportFields = { "spMtId", "spId", "spServiceCode", "channelId", "mtState", "rtState", "batchMtId",
				"sourceAddr", "destinationAddr", "shortMessage", "mtStat", "mtErr", "rtStat", "rtErr", "spMtTime",
				"carrierMtTime", "carrierRtTime", "spRtTime", "countryCode", "provinceCode", "cityCode", "carrierCode",
				"esmClass", "protocolId", "dataCoding" };
		String[] resourceKeys = { "spMtId", "SPID", "SP服务代码", "通道ID", "SMS下行状态", "SMS状态报告状态", "SMS批量下行ID", "源地址",
				"目标地址", "SMS消息", "MT消息状态", "MT错误代码", "RT消息状态", "RT错误代码", "SP端到MLINK端下行的时间", "MLINK端到运营商端下行的时间",
				"运营商端到MLINK端状态报告的时间", "MLINK端到SP端状态报告的时间", "国家代码", "省代码", "市代码", "运营商代码", "ESM_CLASS", "PROTOCOL_ID",
				"DATA_CODING" };
		int i = DataExportUtil.Export(list, exportFields, resourceKeys,
				("企信下行数据表" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "." + exportType), "GBK", Mt.class,
				response, request);
		if (i == 0)
			logger.info("MtSelect export data success");
		else if (i == -1)
			logger.error("MtSelect export data do not support the file type");
		else
			logger.error("MtSelect export data failed");
	}

	/**
	 * 修正基础信息显示国家、省、城市、营运商、消息内容、sp服务代码
	 * 
	 * @param mt
	 */
	private void displaySpMtBaseInfo(Mt mt) {

		if (StringUtil.isNotEmpty(mt.getCarrierCode())) {
			CarrierCode cc = carrierCodeEm.findOne(mt.getCarrierCode());
			if (cc != null)
				mt.setCarrierCode(cc.getCarrierCode() + "-" + cc.getCarrierName());
		}
		if (StringUtil.isNotEmpty(mt.getCountryCode())) {
			Country country = countryEm.findOne(mt.getCountryCode());
			if (country != null)
				mt.setCountryCode(country.getCountryCode() + "-" + country.getCountryName());
		}
		if (StringUtil.isNotEmpty(mt.getProvinceCode())) {
			Province province = provinceEm.findOne(mt.getProvinceCode());
			if (province != null)
				mt.setProvinceCode(province.getProvinceCode() + "-" + province.getProvinceName());
		}
		if (StringUtil.isNotEmpty(mt.getCityCode())) {
			City city = cityEm.findOne(mt.getCityCode());
			if (city != null)
				mt.setCityCode(city.getCityCode() + "-" + city.getCityName());
		}
		if (StringUtil.isNotEmpty(mt.getShortMessage()) && mt.getDataCoding() != null) {
			mt.setShortMessage(StringUtil.decodeHexString(mt.getDataCoding(), mt.getShortMessage()));
		}
		if (StringUtil.isNotEmpty(mt.getSpId())) {
			// SpServicePK ssp = new SpServicePK();
			// ssp.setSpId(mt.getSpId());
			// ssp.setSpServiceCode(mt.getSpServiceCode());
			// SpService spService = spServiceEm.findOne(ssp);
			OldSpServicePK ssp = new OldSpServicePK();
			ssp.setSpId(mt.getSpId());
			ssp.setSpServiceCode(mt.getSpServiceCode());
			OldSpService spService = spServiceEm.findOne(ssp);
			if (spService != null)
				mt.setSpServiceCode(mt.getSpServiceCode() + "(" + spService.getSpServiceName() + ")");
		}
	}

	@RequestMapping(UrlConstants.QYDX_QXXXGL_MTSELECT_AUTOCOMPLETE_SP_SERVICECODE)
	@ResponseBody
	public List<Autocomplete> autoSpserviceSpServiceCode(String term, String spIdName) {

		return AutocompleteUtil.object2auto(spServiceEm.autoSpServiceCode(term, spIdName.split("-")[0]));
	}

	@RequestMapping(UrlConstants.QYDX_QXXXGL_MTSELECT_AUTOCOMPLETE_SP)
	@ResponseBody
	public List<Autocomplete> autoSpmtrouteSp(String term) {

		return AutocompleteUtil.object2auto(spEm.autoSP(term));
	}

	@RequestMapping(UrlConstants.QYDX_QXXXGL_MTSELECT_AUTOCOMPLETE_CHANNEL)
	@ResponseBody
	public List<Autocomplete> autoSpmtrouteChannel(String term) {

		return AutocompleteUtil.object2auto(channelEm.autoChannel(term));
	}

	@RequestMapping(UrlConstants.QYDX_QXXXGL_AUTOCOMPLETE_COUNTRY)
	@ResponseBody
	public List<Autocomplete> autoCountry(String term) {

		List<Autocomplete> country = new ArrayList<>();
		country.addAll(AutocompleteUtil.object2auto(countryEm.auto(term)));

		return country;
	}

	@RequestMapping(UrlConstants.QYDX_QXXXGL_AUTOCOMPLETE_PROVINCE)
	@ResponseBody
	public List<Autocomplete> autoProvince(String countryIdName, String term) {

		List<Autocomplete> province = new ArrayList<>();
		province.addAll(AutocompleteUtil.object2auto(provinceEm.auto(countryIdName.split("-")[0], term)));

		return province;
	}

	@RequestMapping(UrlConstants.QYDX_QXXXGL_AUTOCOMPLETE_CITY)
	@ResponseBody
	public List<Autocomplete> autoCity(String provinceIdName, String term) {

		List<Autocomplete> city = new ArrayList<>();
		city.addAll(AutocompleteUtil.object2auto(cityEm.auto(provinceIdName.split("-")[0], term)));

		return city;
	}

	@RequestMapping(UrlConstants.QYDX_QXXXGL_AUTOCOMPLETE_CARRIERCODE)
	@ResponseBody
	public List<Autocomplete> autoCarriercode(String term) {

		return AutocompleteUtil.object2auto(carrierCodeEm.auto(term));
	}

}
